#include "app_log.h"
#include "app_adc.h"
#include "app_adc_dma.h"
#include "app_io.h"

/*
 * DEFINES
 *****************************************************************************************
 */
#define TEST_CONV_LENGTH      (16UL)

/*
 * GLOBAL VARIABLE DEFINITIONS
 *****************************************************************************************
 */
volatile uint16_t covn_done = 0;
uint16_t conversion[TEST_CONV_LENGTH];
double   voltage[TEST_CONV_LENGTH];
app_adc_params_t adc_params = {
    .pin_cfg = {
        .channel_p = {
            .type = APP_IO_TYPE_MSIO,
            .mux  = APP_ADC_P_INPUT_PIN_MUX,
            .pin  = APP_ADC_P_INPUT_PIN,
        },
        .channel_n = {
            .type = APP_IO_TYPE_MSIO,
            .mux  = APP_ADC_N_INPUT_PIN_MUX,
            .pin  = APP_ADC_N_INPUT_PIN,
        },
    },
    .dma_cfg = {
        .dma_instance = DMA0,
        .dma_channel  = DMA_Channel0,
    },
    .init = {
        .channel_p  = APP_ADC_P_INPUT_SRC,
        .channel_n  = APP_ADC_N_INPUT_SRC,
        .input_mode = ADC_INPUT_SINGLE,
        .ref_source = ADC_REF_SRC_BUF_INT,
        .ref_value  = ADC_REF_VALUE_1P6,
        .clock      = ADC_CLK_1M,
    },
};
void app_adc_evt_handler(app_adc_evt_t * p_evt)
{
    if (p_evt->type == APP_ADC_EVT_CONV_CPLT)
    {
        covn_done = 1;
        printf("DMA conversion is done.\r\n");
    }
}
void vbattery_measure(void)
{
    double vbat;

    adc_params.init.channel_n = ADC_INPUT_SRC_BAT;
    adc_params.init.ref_value = ADC_REF_VALUE_0P8;
    app_adc_deinit();
    app_adc_init(&adc_params, app_adc_evt_handler);
    app_adc_dma_deinit();
    app_adc_dma_init(&adc_params);

    memset(conversion, 0, sizeof(conversion));
    printf("\r\nStart Vbattery sampling.\r\n");
    covn_done = 0;
    app_adc_dma_conversion_async(conversion, TEST_CONV_LENGTH);
    while(covn_done == 0);

    uint32_t aver = 0;
    for(uint32_t i = 0; i<TEST_CONV_LENGTH; i++)
    {
        aver = aver + conversion[i];
    }
    aver = aver/(TEST_CONV_LENGTH);
    printf("Average Vbattery cocdes = %d\r\n", aver);

   // app_adc_vbat_conv((uint16_t *)&aver, &vbat, 1);
    printf("Vbattery= %0.3f V\r\n", vbat);
    app_log_flush();
}